package com.self.liu.xp.base;

import java.net.Socket;
import java.util.List;

import org.apache.log4j.Logger;

import com.self.liu.xp.zk.ZkManager;

public class ThriftServerListener extends Thread {

    /* log */
    private static Logger logger = Logger.getLogger(ThriftServerListener.class);

    /* 本地IP */
    private static final String LOCALHOST = "127.0.0.1";

    /* 等待的秒数 */
    private int waitingtime;

    /* 是否继续等待Flag */
    private boolean isContinueWaiting = true;

    /* 监控程序运行状态 */
    private boolean isRunning = false;

    /* 配置监听服务的所有端口号 */
    private List<Integer> ports;

    /* 配置监听服务IP */
    private String ip;

    /*
     * 启动监听
     */
    public void open() {
        super.start();
        logger.info("ThriftServerListener is openning...");
    }

    /*
     * 关闭监听
     */
    public void close() {
        ZkManager.close();
        logger.info("ZkClient is close...");
        //定时2秒等待
        waiting(2000L);
        isContinueWaiting = false;
        while (isRunning) {
            //定时1秒等待
            waiting(1000L);
        }
        ThriftApplication.stop();
        logger.info("ThriftServerListener is closed.");
    }

    @Override
    public void run() {
        super.run();
        //设定为运行中
        isRunning = true;
        logger.info("Thrift 服务监听程序，已启动。");
        //启动Thrift应用
        ThriftApplication.start();
        //5秒后循环监听Thrift应用
        waiting(5000L);
        while (isContinueWaiting) {
            for (int i = 0; i < ports.size(); i++) {
                int port = ports.get(i);
                //判断端口服务是否启动
                if (isServiceOpened(port)) {
                    logger.debug("Port-" + port + " Server is running...");
                    String url = ip + ":" + port;
                    if (!ZkManager.isReged(url)) {
                        ZkManager.reg(url);
                        logger.info("Port-" + port + " Server is reg");
                    }
                } else {
                    logger.error("Port-" + port + " Server is not running,restarting...");
                    //重启Thrift应用
                    ThriftApplication.stop();
                    ThriftApplication.start();
                    //5秒后重新循环监听Thrift应用
                    waiting(5000L);
                }
            }
            //定时等待
            waiting(waitingtime * 1000);
        }
        logger.info("Thrift 服务监听程序，已停止。");
        //设定为运行结束
        isRunning = false;
    }

    /*
     * 等待N毫秒
     * 
     * @param millis 等待的毫秒数
     * 
     */
    private void waiting(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            logger.error("Thrift 监听程序等待异常。Case:" + e.getMessage());
        }
    }

    /*
     * 判断服务是否开启
     * 
     * @param port:服务端口号
     * 
     * @rerun true:开放中 false:未开放
     */
    private boolean isServiceOpened(int port) {
        Socket clientSocket = null;
        try {
            clientSocket = new Socket(LOCALHOST, port);
            clientSocket.close();
            return true;
        } catch (Exception e) {
            logger.error("Port-" + port + " connection failed. Case:" + e.getMessage());
            return false;
        }
    }

    public List<Integer> getPorts() {
        return ports;
    }

    public void setPorts(List<Integer> ports) {
        this.ports = ports;
    }

    public int getWaitingtime() {
        return waitingtime;
    }

    public void setWaitingtime(int waitingtime) {
        this.waitingtime = waitingtime;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

}
